﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using SSTU.Contract.Interaction;
using SSTU.Management.Dependency;
using SSTU.Contract.Common;

namespace SSTU.ViewModel.Core
{
	/// <summary>
	/// Base class for application view models.
	/// </summary>
	public class AppViewModelBase : ViewModelBase
	{
		private bool _isBusy;
		private string _busyText;

		/// <summary>
		/// Create 
		/// </summary>
		public AppViewModelBase()
		{
			BusyText = "Загрузка...";
			IsBusy = false;
		}

		/// <summary>
		/// Gets or sets flag which indicates that view model now is busy.
		/// </summary>
		public bool IsBusy
		{
			get { return _isBusy; }
			set
			{
				if (value != _isBusy)
				{
					RaisePropertyChanging<bool>(() => IsBusy);
					_isBusy = value;
					RaisePropertyChanged<bool>(() => IsBusy);
				}
			}
		}

		/// <summary>
		/// Gets or sets message text for 'busy' state.
		/// </summary>
		public string BusyText
		{
			get { return _busyText; }
			set
			{
				if (value != _busyText)
				{
					RaisePropertyChanging<string>(() => BusyText);
					_busyText = value;
					RaisePropertyChanged<string>(() => BusyText);
				}
			}
		}

		protected void DoWithBusy(Action action)
		{
			try
			{
				IsBusy = true;
				action();
			}
			catch (Exception)
			{
				IsBusy = false;
				throw;
			}
		}

		protected void DisplayMessage(string message)
		{
			if ((App.Current != null) && (App.Current.RootVisual != null))
			{
				App.Current.RootVisual.Dispatcher.BeginInvoke(() => MessageBox.Show(message));
			}
		}

		protected void DisplayError(Exception error = null, string message = null)
		{
			if ((App.Current != null) && (App.Current.RootVisual != null))
			{
				string messageText = message ?? (error == null ? "Произошла неизвестная ошибка" : error.ToString());
				App.Current.RootVisual.Dispatcher.BeginInvoke(() => MessageBox.Show(messageText));
			}
		}

		protected void DisplayError(FacadeResponseDataSource dataSource, string subjectWhatLoaded, Exception error = null)
		{
			if ((App.Current != null) && (App.Current.RootVisual != null))
			{
				string messageTextPattern =
					dataSource == FacadeResponseDataSource.Server ?
					"При загрузке {0} с сайта/сервера, произошла ошибка." :
					dataSource == FacadeResponseDataSource.Local ?
					"При загрузке {0} из памяти устройства, произошла ошибка."
					: "При загрузке {0}, произошла неизвестная ошибка.";
				string messageText = string.Format(messageTextPattern, subjectWhatLoaded ?? "данных");
				App.Current.RootVisual.Dispatcher.BeginInvoke(() => MessageBox.Show(messageText));
			}
		}
	}
}
